/*项目信息管理*/
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:frametrim/appviews/pojectMessMarkView.dart';
import 'package:frametrim/http/ApiUtils.dart';
import 'package:frametrim/http/HttpManager.dart';
import 'package:frametrim/model/DistrictCommonM.dart';
import 'package:frametrim/model/ProjectMessManagerM.dart';
import 'package:frametrim/route/Routes.dart';
import 'package:frametrim/utility/Tools.dart';
import 'package:frametrim/utility/sq_color.dart';
import 'package:frametrim/views/MyUnderlineTabIndicator.dart';
import 'package:frametrim/views/appbar_search_toAppbar.dart';
import 'package:frametrim/views/background_view.dart';
import 'package:frametrim/views/button_round.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class ProjectMessManagerPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => ProjectMessManagerState();
}

class ProjectMessManagerState extends State<ProjectMessManagerPage>
    with TickerProviderStateMixin {
  //TickerProviderStateMixin
  TextEditingController _controller = TextEditingController();

  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  final List<Tab> myTabs = [];

  //头部-审核状态
  List<DepartmentList> mTablist = [];

  //项目类别
  List<DepartmentList> mProjectType = [];

  //项目列表
  List<ProjectMessManagerRecords> mData = [];

  late TabController _tabController; //需要定义一个Controller

  //项目状态 0：再建 1竣工 2停工 3 新批 4完工待验收  默认搜索全部
  var state = "";
  var currentPage = 1;

  // EasyRefreshController _refreshController = new EasyRefreshController();
  var isLoading = true;

  @override
  void initState() {
    super.initState();
    // 创建Controller
    _tabController = TabController(length: myTabs.length, vsync: this);
    //获取头部
    getDistrictData('PROJECT_STATE');
    //获取项目类别
    getDistrictData('PROJECT_TYPE');
    //获取列表
    getData("");
  }

  @override
  void dispose() {
    super.dispose();
    _tabController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: SQColor.color_background,
        appBar: AppBar(
          backgroundColor: Colors.white,
          titleSpacing: 0,
          elevation: 0,
          title: AppbarSearchUseAppBarTitle(
            imgStr: 'image/imv_back.png',
            controller: _controller,
            callback: (str) {},
            isNeedJump: true,
            isShowSearchImg: false,
          ),
          leadingWidth: 0,
          bottom: TabBar(
            controller: _tabController,
            tabs: myTabs,
            // 定义TabWeight,若数量和定义不一致会报错
            onTap: (int index) {
              print('Selected......$index');
              currentPage = 1;
              getState(index);
              getData("");
            },
            //设置未选中时的字体颜色，tabs里面的字体样式优先级最高
            unselectedLabelColor: SQColor.color_90black,
            //设置未选中时的字体样式，tabs里面的字体样式优先级最高
            unselectedLabelStyle: TextStyle(fontSize: 16),
            //设置选中时的字体颜色，tabs里面的字体样式优先级最高
            labelColor: SQColor.color_90black,
            //设置选中时的字体样式，tabs里面的字体样式优先级最高
            labelStyle: TextStyle(fontSize: 16.0),
            //允许左右滚动
            isScrollable: true,
            indicator: MyUnderlineTabIndicator(
                borderSide:
                    BorderSide(width: 3.0, color: SQColor.color_0052D9)),
          ),
        ),
        body: Column(
          children: [
            Divider(height: 1, color: SQColor.color_DEDEDE),
            Expanded(child: SmartRefresher(
                enablePullDown: true,
                enablePullUp: true,
                controller: _refreshController,
                onRefresh: () async {
                  currentPage = 1;
                  getData("");
                },
                onLoading: () async {
                  currentPage++;
                  getData("");
                },
                child: ListView.builder(
                  shrinkWrap: true,
                  itemBuilder: (context, index) {
                    return buildItem(mData[index]);
                  },
                  itemCount: mData.length,

                )))
          ],
        ));
  }

  //搜索
  search() {}

  /**
   * item布局
   */
  Widget buildItem(ProjectMessManagerRecords data) {
    return GestureDetector(
      onTap: () {
        Get.toNamed(Routes.PROJECT_MESS_MANAGER_DETAILS,
            arguments: {"id": "${data.id}"});
      },
      child: BackgroundView(
        mVerticalTopMargin: 10,
        mVerticalBottomMargin: 0,
        widget: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                //状态
                buildStateWidget(data),
                Expanded(child: Container()),
                Text(getCheckState(data),
                    style: TextStyle(fontSize: 14, color: SQColor.color_3D3D3D))
              ],
            ),
            SizedBox(height: 10),
            //标题
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(
                    child: Text(data.name!,
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            fontSize: 16, color: SQColor.color_3D3D3D))),
              ],
            ),
            SizedBox(height: 15),
            Text('建设单位：${Tools.TextNullToLine(data.constructionUnitName)}',
                style: TextStyle(fontSize: 14, color: SQColor.color_3D3D3D)),
            SizedBox(height: 8),
            Text(
                '项目区域：${Tools.TextNullToLine(data.projectProvinceName)}/${Tools.TextNullToLine(data.projectCityName)}/${Tools.TextNullToLine(data.projectCountyName)}',
                style: TextStyle(fontSize: 14, color: SQColor.color_3D3D3D)),
            SizedBox(height: 8),
            Text(
                '项目类别：${getProjectTypeName(Tools.TextNullToLine(data.type.toString()))}',
                style: TextStyle(fontSize: 14, color: SQColor.color_3D3D3D)),
            SizedBox(height: 10),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: buildButtons(data),
            ),
          ],
        ),
      ),
    );
  }

  //项目状态  在建、停工、完工待验收、竣工、新批
  Widget buildStateWidget(ProjectMessManagerRecords data) {
    Widget? child;
    var state = data.state;
    if (state == 0) {
      child = ProjectMessMarkView(
          borderColor: SQColor.color_0052D9,
          fullrColor: SQColor.color_ECF2FE,
          content: '在建');
    } else if (state == 1) {
      child = ProjectMessMarkView(
          borderColor: SQColor.color_ED7B2F,
          fullrColor: SQColor.color_FEF3E6,
          content: '竣工');
    } else if (state == 2) {
      child = ProjectMessMarkView(
          borderColor: SQColor.color_E34D59,
          fullrColor: SQColor.color_FDECEE,
          content: '停工');
    } else if (state == 3) {
      child = ProjectMessMarkView(
          borderColor: SQColor.color_067945,
          fullrColor: SQColor.color_E8F8F2,
          content: '新批');
    } else if (state == 4) {
      child = ProjectMessMarkView(
          borderColor: SQColor.color_ED7B2F,
          fullrColor: SQColor.color_FEF3E6,
          content: '完工待验收');
    }
    return child!;
  }

  //获取审核状态   -1待完善 0待审核 1审核通过 2审核驳回
  //   var mCheckState='';
  String getCheckState(ProjectMessManagerRecords data) {
    var mCheckState = '';
    var mCheck = data.checkStatus;
    if (mCheck == -1) {
      mCheckState = "待完善";
    } else if (mCheck == 0) {
      mCheckState = "待审核";
    } else if (mCheck == 1) {
      mCheckState = "审核通过";
    } else if (mCheck == 2) {
      mCheckState = "审核驳回";
    }
    return mCheckState;
  }

  //获取项目类别name
  getProjectTypeName(String id) {
    var name = "";
    mProjectType.forEach((element) {
      if (id == element.id.toString()) {
        name = element.name!;
      }
    });
    return name;
  }

  /**
   * 下部按钮
   *  项目状态 0：再建 1竣工 2停工 3 新批 4完工待验收
   *  获取审核状态   -1待完善 0待审核 1审核通过 2审核驳回
   */
  List<Widget> buildButtons(ProjectMessManagerRecords data) {
    List<Widget> children = [];
    if (data.checkStatus == -1) {
      children.add(
          buildAnNiu('删除', SQColor.color_90black, SQColor.color_C5C5C5, () {}));
      children.add(SizedBox(width: 20));
      children
          .add(buildAnNiu('编辑', SQColor.white, SQColor.color_0052D9, () {}));
    } else if (data.checkStatus == 0) {
      children
          .add(buildAnNiu('审核', SQColor.white, SQColor.color_0052D9, () {}));
    }
    return children;
  }

  //按钮
  Widget buildAnNiu(
      String text, Color textColor, Color buttonColor, VoidCallback? onPress) {
    return ButtonRoundView(
        mVerticalPadding: 10,
        mHorizontalPadding: 15,
        textStr: text,
        textColor: textColor,
        textSize: 14,
        buttonColor: buttonColor,
        onPress: onPress);
  }

  /**
   * 接口
   */
//字典项
  getDistrictData(String commonCode) async {
    var map = Map<String, dynamic>();
    map["commonCode"] = commonCode;
    HttpManager.getInstance()
        .addHeader()
        .postJson(context, ApiUtils.getDistrictCommon, params: map,
            successCallBack: (dataMap) {
      DistrictCommonM model = DistrictCommonM.fromJson(dataMap);
      //项目审核状态
      if (commonCode == "PROJECT_STATE") {
        mTablist.clear();
        var departmentList = model.records?.departmentList;
        mTablist.addAll(departmentList!);
        setState(() {
          myTabs.clear();
          myTabs.add(Tab(text: '全部'));
          mTablist.forEach((element) {
            myTabs.add(Tab(text: element.name));
          });
          _tabController =
              new TabController(length: myTabs.length, vsync: this);
        });
      } else if (commonCode == "PROJECT_TYPE") {
        mProjectType.clear();
        var departmentList = model.records?.departmentList;
        mProjectType.addAll(departmentList!);
      }
    });
  }

  //列表数据
  getData(String keyWord) {
    var map = Map<String, dynamic>();
    map["current"] = currentPage;
    map["size"] = "20";
    map["state"] = state;
    if (keyWord.isNotEmpty) {
      map["name"] = keyWord;
    }
    HttpManager.getInstance()
        .addHeader()
        .post(context, ApiUtils.projectmanageList, params: map,
            successCallBack: (dataMap) {
      ProjectMessManagerM model = ProjectMessManagerM.fromJson(dataMap);
      showData(model);
    }, afterCallBack: () {
      // _refreshController.loadNoData();
      _refreshController.refreshCompleted();
      _refreshController.loadComplete();
    });
  }

  showData(ProjectMessManagerM model) {
    if (currentPage == 1) {
      mData.clear();
    }
    var list = model.records?.records;
    setState(() {
      mData.addAll(list!);
    });
  }

  /**
   * 获取某项目状态
   */
  getState(int index) {
    mTablist.forEach((element) {
      if (myTabs[index].text == element.name) {
        state = element.id.toString();
      }
    });
  }
}
